from flask import Blueprint, request, jsonify
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime, UTC
from applications.extensions import db  # 假设您的 db 实例在这里
from applications.models import Admin, Role, Permission  # 假设您的模型在 models.py 中
from applications.view.system.decorators import require_permission

# 创建 admin 蓝图
admin_bp = Blueprint('admin_bp', __name__, url_prefix='/system/admin')


# --- 用户管理 (Admin Management) ---

# 获取所有管理员列表
@admin_bp.route('/users', methods=['GET'])
# @require_permission('view_users')  # 应用装饰器，只有具备 'view_users' 权限的用户才能访问
def get_users():
    """获取所有管理员列表"""
    users = Admin.query.all()
    user_list = []
    for user in users:
        user_data = {
            'id': user.id,
            'username': user.username,
            'email': user.email,
            'phone': user.phone,
            'created_at': user.created_at.isoformat() if user.created_at else None,
            'status': user.status,
            'nickname': user.nickname,
            'real_name': user.real_name,
            'sex': user.sex,
            'address': user.address,
            'introduction': user.introduction,
            'last_login_at': user.last_login_at.isoformat() if user.last_login_at else None,
            'last_login_ip': user.last_login_ip
        }
        user_list.append(user_data)
    return jsonify({
        'code': 200,
        'data': {
            'list': user_list,
            'total': len(users)
        }

    })


# 创建新管理员
@admin_bp.route('/users', methods=['POST'])
def create_user():
    """创建新管理员"""
    data = request.get_json()
    if not data or 'username' not in data or 'password' not in data:
        return jsonify({'message': 'Username and password are required'}), 400

    username = data.get('username')
    password = data.get('password')
    email = data.get('email')
    phone = data.get('phone')
    nickname = data.get('nickname')
    real_name = data.get('real_name')
    birthday = data.get('birthday')  # 预期格式 "YYYY-MM-DD"
    sex = data.get('sex')
    address = data.get('address')
    introduction = data.get('introduction')

    # 检查用户名是否已存在
    if Admin.query.filter_by(username=username).first():
        return jsonify({'message': 'Username already exists'}), 409

    hashed_password = generate_password_hash(password)
    new_admin = Admin(
        username=username,
        password=hashed_password,
        email=email,
        phone=phone,
        nickname=nickname,
        real_name=real_name,
        birthday=datetime.strptime(birthday, '%Y-%m-%d').date() if birthday else None,
        sex=sex,
        address=address,
        introduction=introduction,
        created_at=datetime.now(UTC)
    )

    db.session.add(new_admin)
    db.session.commit()
    return jsonify({'message': 'Admin created successfully', 'user_id': new_admin.id}), 201


# 获取管理员详情
@admin_bp.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
    """获取指定管理员详情"""
    user = Admin.query.get(user_id)
    if not user:
        return jsonify({'message': 'User not found'}), 404

    user_data = {
        'id': user.id,
        'username': user.username,
        'email': user.email,
        'phone': user.phone,
        'created_at': user.created_at.isoformat() if user.created_at else None,
        'status': user.status,
        'nickname': user.nickname,
        'real_name': user.real_name,
        'birthday': user.birthday.isoformat() if user.birthday else None,
        'sex': user.sex,
        'address': user.address,
        'introduction': user.introduction,
        'last_login_at': user.last_login_at.isoformat() if user.last_login_at else None,
        'last_login_ip': user.last_login_ip
    }
    return jsonify(user_data), 200


# 更新指定管理员信息
@admin_bp.route('/users/<int:user_id>', methods=['PUT'])
def update_admin_user(user_id):
    """更新指定管理员信息"""
    user = Admin.query.get(user_id)
    if not user:
        return jsonify({'message': 'User not found'}), 404

    data = request.get_json()
    if not data:
        return jsonify({'message': 'No update data provided'}), 400

    user.username = data.get('username', user.username)
    user.email = data.get('email', user.email)
    user.phone = data.get('phone', user.phone)
    user.nickname = data.get('nickname', user.nickname)
    user.real_name = data.get('real_name', user.real_name)
    if 'birthday' in data and data['birthday']:
        try:
            user.birthday = datetime.strptime(data['birthday'], '%Y-%m-%d').date()
        except ValueError:
            return jsonify({'message': 'Invalid birthday format. Use YYYY-MM-DD.'}), 400
    elif 'birthday' in data and data['birthday'] is None:
        user.birthday = None  # 允许清空生日
    sex_raw = data.get('sex')
    if sex_raw == '' or sex_raw is None:
        user.sex = None  # 业务默认 0-未知
    else:
        user.sex = int(sex_raw)
    user.address = data.get('address', user.address)
    user.introduction = data.get('introduction', user.introduction)
    user.status = data.get('status', user.status)  # 允许更新状态

    # 如果更新了密码，需要重新哈希
    if 'password' in data and data['password']:
        user.password = generate_password_hash(data['password'])

    db.session.commit()
    return jsonify({'message': 'U用户更新成功！'}), 200


# 删除指定管理员
@admin_bp.route('/users/<int:user_id>', methods=['DELETE'])
@require_permission('delete_user')  # 需要 'delete_user' 权限
def delete_admin_user(user_id):
    """删除指定管理员"""
    user = Admin.query.get(user_id)
    if not user:
        return jsonify({'message': 'User not found'}), 404

    # 避免删除超级管理员，或者根据业务逻辑添加其他保护
    # if user.username == 'super_admin':
    #     return jsonify({'message': 'Cannot delete super admin'}), 403

    db.session.delete(user)
    db.session.commit()
    return jsonify({'message': 'User deleted successfully'}), 200


# 重置管理员用户密码
@admin_bp.route('/users/<int:user_id>/reset-password', methods=['POST'])
def admin_reset_pwd(user_id):
    """重置用户密码"""
    user = Admin.query.get(user_id)
    if not user:
        return jsonify({'code': 404, 'message': '未找到用户'}), 404

    data = request.get_json()
    if not data or 'password' not in data or not data['password']:
        return jsonify({'code': 400, 'message': '请输入新密码！'}), 400

    new_password = data.get('password')
    user.password = generate_password_hash(new_password)
    db.session.commit()

    return jsonify({'code': 200, 'message': '密码重置成功！'})


# 为管理员分配角色
@admin_bp.route('/users/<int:user_id>/assign_roles', methods=['POST'])
def assign_roles_to_user(user_id):
    """为管理员分配角色"""
    user = Admin.query.get(user_id)
    if not user:
        return jsonify({'message': 'User not found'}), 404

    data = request.get_json()
    if not data or 'role_ids' not in data or not isinstance(data['role_ids'], list):
        return jsonify({'message': 'Invalid request body. Provide a list of role_ids.'}), 400

    role_ids = data['role_ids']
    roles_to_assign = Role.query.filter(Role.id.in_(role_ids)).all()

    # 检查所有提供的 role_ids 是否都存在
    if len(roles_to_assign) != len(role_ids):
        return jsonify({'message': 'One or more roles not found'}), 404

    user.roles = roles_to_assign
    db.session.commit()
    return jsonify({'message': f'成功为用户分配角色 {user_id}'}), 200


# 获取管理员当前的角色
@admin_bp.route('/users/<int:user_id>/roles', methods=['GET'])
def get_user_roles(user_id):
    """获取管理员当前的角色"""
    user = Admin.query.get(user_id)
    if not user:
        return jsonify({'message': 'User not found'}), 404

    user_roles_data = []
    for role in user.roles:
        user_roles_data.append({
            'id': role.id,
            'name': role.name,
            'code': role.code,
            'remark': role.remark,
            'status': role.status
        })
    return jsonify({'code': 200, 'data': user_roles_data})


# 注册管理端用户蓝图
def register_admin_bps(app):
    app.register_blueprint(admin_bp)
